/**
 * 
 */
package com.common.distributed.sharding.algorithm.client.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.common.distributed.sharding.algorithm.DataBaseSchemaHashShard;
import com.common.distributed.sharding.algorithm.TableBeanHashShard;
import com.common.distributed.sharding.algorithm.client.IDistributedClient;
import com.common.distributed.sharding.algorithm.support.TableBean;
import com.common.distributed.sharding.spring.schema.DataBaseSchema;
import com.common.distributed.sharding.spring.schema.DistributedClientSchema;
import com.common.distributed.sharding.spring.schema.TableSchema;
/**
 * @author liubing
 * 分布式分库分表算法核心
 */
public class DistributedClientImpl implements IDistributedClient {

	@Override
	public DataBaseSchema getShardDataSoure(
			DistributedClientSchema distributedClientSchema,
			String tablenamefield) {
		// TODO Auto-generated method stub
		Map<String, DataBaseSchema> map=distributedClientSchema.getMap();
		List<DataBaseSchema> dataBaseSchemas=new ArrayList<DataBaseSchema>();
		String tablename="";
		Boolean flag=false;
		for(String key:map.keySet()){//找出跳出循环
			List<TableSchema> tableSchemas=map.get(key).getTableSchemas();
			for(TableSchema tableSchema:tableSchemas){
				if(tableSchema.getTablefield().equals(tablenamefield)){
					tablename=tableSchema.getTablename();
					flag=true;
					break;
				}
			}
			if(flag){
				break;
			}
		}
		Map<String, Set<String>> tablenameMapingDatasources=distributedClientSchema.collectTablenameMapingDatasource();
		Set<String> databases=tablenameMapingDatasources.get(tablename);
		for(String database:databases){
			dataBaseSchemas.add(distributedClientSchema.getMap().get(database));
		}
		DataBaseSchemaHashShard baseSchemaHashShard=new DataBaseSchemaHashShard(dataBaseSchemas);
		return baseSchemaHashShard.getShardInfo(tablenamefield);
	}

	@Override
	public TableBean getShardTableName(
			DistributedClientSchema distributedClientSchema,
			String tablenamefield, String databsename) {
		// TODO Auto-generated method stub
		Map<String, List<TableSchema>> maps=distributedClientSchema.collectDataBaseMappingTablename();
		List<TableSchema> tableSchemas=maps.get(databsename);
		TableSchema result=new TableSchema();
		for(TableSchema tableSchema:tableSchemas){
			if(tableSchema.getTablefield().equals(tablenamefield)){
				result=tableSchema;
				break;
			}
		}
		
		List<TableBean> tableBeans=new ArrayList<TableBean>();
		for(int i=0;i<result.getCount();i++){
			TableBean tableBean=new TableBean();
			tableBean.setName(result.getTablename());
			tableBean.setPrefixname(result.getPrefixname()+i);
			tableBeans.add(tableBean);
		}
		TableBeanHashShard beanHashShard=new TableBeanHashShard(tableBeans);
		return beanHashShard.getShardInfo(tablenamefield);
	}

}
